package com.css.zfzx.sjcj.modules.hddcLava.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcLava.repository.HddcLavaNativeRepository;
import com.css.zfzx.sjcj.modules.hddcLava.repository.HddcLavaRepository;
import com.css.zfzx.sjcj.modules.hddcLava.repository.entity.HddcLavaEntity;
import com.css.zfzx.sjcj.modules.hddcLava.service.HddcLavaService;
import com.css.zfzx.sjcj.modules.hddcLava.viewobjects.HddcLavaQueryParams;
import com.css.zfzx.sjcj.modules.hddcLava.viewobjects.HddcLavaVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zhangcong
 * @date 2020-11-27
 */
@Service
public class HddcLavaServiceImpl implements HddcLavaService {

	@Autowired
    private HddcLavaRepository hddcLavaRepository;
    @Autowired
    private HddcLavaNativeRepository hddcLavaNativeRepository;

    @Override
    public JSONObject queryHddcLavas(HddcLavaQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcLavaEntity> hddcLavaPage = this.hddcLavaNativeRepository.queryHddcLavas(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcLavaPage);
        return jsonObject;
    }


    @Override
    public HddcLavaEntity getHddcLava(String id) {
        HddcLavaEntity hddcLava = this.hddcLavaRepository.findById(id).orElse(null);
         return hddcLava;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcLavaEntity saveHddcLava(HddcLavaEntity hddcLava) {
        String uuid = UUIDGenerator.getUUID();
        hddcLava.setUuid(uuid);
        hddcLava.setCreateUser(PlatformSessionUtils.getUserId());
        hddcLava.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcLava.setIsValid("1");
        this.hddcLavaRepository.save(hddcLava);
        return hddcLava;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcLavaEntity updateHddcLava(HddcLavaEntity hddcLava) {
        UpdateUtil.copyNullProperties(hddcLavaRepository.findByUuidAndIsValid(hddcLava.getUuid(), "1"), hddcLava);
        hddcLava.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcLava.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcLavaRepository.save(hddcLava);
        return hddcLava;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcLavas(List<String> ids) {
        List<HddcLavaEntity> hddcLavaList = this.hddcLavaRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcLavaList) && hddcLavaList.size() > 0) {
            for(HddcLavaEntity hddcLava : hddcLavaList) {
                hddcLava.setIsValid("0");
                hddcLava.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcLava.setUpdateTime(new Date());
                this.hddcLavaRepository.save(hddcLava);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcLavaQueryParams queryParams, HttpServletResponse response) {
        List<HddcLavaEntity> yhDisasterEntities = hddcLavaNativeRepository.exportYhDisasters(queryParams);
        List<HddcLavaVO> list=new ArrayList<>();
        for (HddcLavaEntity entity:yhDisasterEntities) {
            HddcLavaVO yhDisasterVO=new HddcLavaVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "熔岩流-面", "熔岩流-面", HddcLavaVO.class, "熔岩流-面.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcLavaVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcLavaVO.class, params);
            List<HddcLavaVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcLavaVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcLavaVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcLavaVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcLavaEntity yhDisasterEntity = new HddcLavaEntity();
            HddcLavaVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcLava(yhDisasterEntity);
        }
    }

}
